package com.example.userservice.controller;

import com.example.userservice.service.CodeServiceFeignClient;
import com.example.userservice.service.TokenService;
import com.example.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author zhouyp
 * @program example-parent
 * @description
 * @create 2020-07-27
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

	@Autowired
	private CodeServiceFeignClient codeServiceFeignClient;
	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;

	@RequestMapping("/register/{email}/{password}/{code}")
	public String register(@PathVariable String email,
	                       @PathVariable String password,
	                       @PathVariable String code) {
		int validate = codeServiceFeignClient.validate(email, code);
		if (0 == validate) {
			if (userService.register(email, password)) {
				return "0";
			}
		} else if (1 == validate) {
			return "验证码校验失败";
		} else if (2 == validate) {
			return "验证码失效";
		}
		return "未知异常";
	}

	@RequestMapping("/isRegistered/{email}")
	public boolean isRegistered(@PathVariable String email) {
		return userService.isRegistered(email);
	}

	@RequestMapping("/login/{email}/{password}")
	public String login(@PathVariable String email,
	                    @PathVariable String password) {
		if (userService.login(email, password)) {
			return email;
		}
		throw new RuntimeException("登录失败");
	}

	@RequestMapping("/info/{token}")
	public String infoWithToken(@PathVariable String token) {
		return tokenService.infoWithToken(token);
	}

	@RequestMapping("/info")
	public String infoByCookie(HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return "";
		}
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if ("example-token".equals(cookie.getName())) {
				return tokenService.infoWithToken(cookie.getValue());
			}
		}
		return "";
	}

}
